# !/usr/bin/python3
# -*-coding:utf-8-*-
# Author: sanra
# CreatDate: 2021/1/8 11:11
# Description:

import pika
import uuid


class FibonacciRpcClient(object):
    def __init__(self):

        credentials = pika.PlainCredentials('guest', 'guest')
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(
            host = 'localhost', port = 5672, virtual_host = '/', credentials = credentials))

        self.channel = self.connection.channel()

        result = self.channel.queue_declare(queue = 'rpc_queue', exclusive = False)
        self.callback_queue = result.method.queue

        self.channel.basic_consume(queue = self.callback_queue, on_message_callback = self.on_response, auto_ack = False)

    def on_response(self, ch, method, props, body):
        if self.corr_id == props.correlation_id:
            self.response = body

    def call(self, n):
        self.response = None
        self.corr_id = str(uuid.uuid4())
        self.channel.basic_publish(exchange = '',
                                   routing_key = 'rpc_queue',
                                   properties = pika.BasicProperties(
                                       reply_to = self.callback_queue,
                                       correlation_id = self.corr_id,
                                   ),
                                   body = str(n))
        while self.response is None:
            self.connection.process_data_events()
        return int(self.response.decode())


if __name__ == '__main__':
    fibonacci_rpc = FibonacciRpcClient()
    print(" [x] Requesting fib(30)")
    response = fibonacci_rpc.call(30)
    print(" [.] Got %r" % (response,))
